<?php

namespace app\common\validate;

/**=========================================
 * Copyright © 2023-2024, WICMS.CN. All Rights Reserved
 * Project Name: WiCMS
 * Description: 导航菜单验证器
 * Author: jason
 * Email: 52527998@QQ.COM
 * Date: 2024/12/16
 * Time: 17:36
 * File: app\common\Validate\RouteMenuValidate.php
 * =========================================
 */

use think\facade\Log;
use think\Validate;

class RouteMenuValidate extends Validate
{

    protected $rule = [
        'menu_name|菜单名称'  => 'require|max:25',
        'menu_type|菜单类型'  => 'require|in:menu,btn,iframe,link',
        'pid|上级菜单'        => 'require|integer',
        // menu验证
        'component_path|组件路径' => 'requireIf:menu_type,menu',
        // btn验证
        'permission_code|权限标识' => 'requireIf:menu_type,btn|checkPermissionCode',
        // 非btn验证
        'route_name|路由名称' => 'requireCallback:notBtnRequire',
        'route_path|路由路径' => 'requireCallback:notBtnRequire',
    ];

    protected $message = [];

    protected $scene = [
        'add'    => ['menu_name', 'menu_type', 'pid', 'component_path', 'permission_code', 'route_name', 'route_path'],
        'update' => ['menu_name', 'menu_type', 'pid', 'component_path', 'permission_code', 'route_name', 'route_path']
    ];

    protected function notBtnRequire($value, $data): bool
    {
        return $data['menu_type'] != 'btn';
    }

    protected function checkPermissionCode($value): bool
    {
        if (empty($value)) {
            return '权限标识不能为空';
        }
        // 内容必须格式为 Module@Page.Action
        if (!preg_match('/^[a-zA-Z-_]+@[a-zA-Z-_]+\.[a-zA-Z-_]+$/', $value)) {
            return '权限标识格式不正确';
        }
        return true;
    }
}